package com.service.impl;

import com.bean.entity.Goods;
import com.bean.vo.GoodsVo;
import com.bean.vo.query.GoodsQueryVo;
import com.dao.GoodsMapper;
import com.service.GoodsService;
import com.util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 库存业务逻辑实现
 */
@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    GoodsMapper goodsMapper;

    @Override
    public PageUtil<GoodsVo> queryGoodsByPage(GoodsQueryVo goodsQueryVo, PageUtil<GoodsVo> pa) throws Exception {
        //查询总记录数
        int count = goodsMapper.selectCount(goodsQueryVo);
        pa.setCount(count);
        //判断，查询结果是否为空
        if (count == 0) throw new Exception("未找到符合条件的数据！");
        //判断，查询结果总记录数是否大于当前页数
        if (pa.getCurrPage() > pa.getTotalPage()) pa.setCurrPage(pa.getTotalPage());
        //设置起始序号
        goodsQueryVo.setPageCode(pa.getPageCode());
        goodsQueryVo.setCurrPage(pa.getCurrPage());
        goodsQueryVo.setPageSize(pa.getPageSize());
//        System.out.println(goodsQueryVo);
//        System.out.println(pa);
        //查询分页数据
        List<GoodsVo> goodsList = goodsMapper.selectByPage(goodsQueryVo);
        pa.setItems(goodsList);

        return pa;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeGoods(Goods goods) throws Exception {
        //查询数据
        GoodsVo goodsVo = goodsMapper.select(goods).get(0);
        //判断库存量是否清空
        if (goodsVo.getQuantity() != 0) throw new Exception("物品库存未清空，请确认！");
        //删除库存信息
        int delete = goodsMapper.delete(goods);
        //判断删除结果
        if(delete == 0) throw new Exception("删除失败！");
        //删除成功
        return 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int modifyGoods(Goods goods) throws Exception {
        //修改数据
        int update = goodsMapper.update(goods);
        //判断结果
        if (update == 0) throw new Exception("修改失败！");

        return 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addGoods(Goods goods) throws Exception {
        //添加数据
        int insert = goodsMapper.insert(goods);
        //判断结果
        if (insert == 0) throw new Exception("添加失败！");

        return 1;
    }
}
